#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
队列管理页面模块
"""

import logging
from PyQt6.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton,
    QTabWidget, QFrame, QGridLayout, QLineEdit, QComboBox,
    QCheckBox, QSpinBox, QFileDialog, QMessageBox, QListWidget,
    QListWidgetItem, QTableWidget, QTableWidgetItem, QHeaderView,
    QProgressBar, QDialog, QFormLayout, QDialogButtonBox, QSplitter
)
from PyQt6.QtCore import Qt, QTimer
from PyQt6.QtGui import QIcon, QColor


class QueueSettingsDialog(QDialog):
    """队列设置对话框"""
    
    def __init__(self, queue_data, parent=None):
        super().__init__(parent)
        self.queue_data = queue_data
        self.setWindowTitle(f"队列设置: {queue_data['name']}")
        self.resize(400, 300)
        self._setup_ui()
    
    def _setup_ui(self):
        """设置UI"""
        layout = QVBoxLayout(self)
        
        # 队列信息表单
        form_layout = QFormLayout()
        
        # 队列名称
        self.name_edit = QLineEdit(self.queue_data["name"])
        self.name_edit.setReadOnly(True)  # 不允许修改名称
        form_layout.addRow("队列名称:", self.name_edit)
        
        # 最大并行任务数
        self.max_workers_spinbox = QSpinBox()
        self.max_workers_spinbox.setRange(1, 20)
        self.max_workers_spinbox.setValue(self.queue_data["max_workers"])
        form_layout.addRow("最大并行任务数:", self.max_workers_spinbox)
        
        # 队列优先级
        self.priority_spinbox = QSpinBox()
        self.priority_spinbox.setRange(1, 10)
        self.priority_spinbox.setValue(self.queue_data["priority"])
        form_layout.addRow("队列优先级:", self.priority_spinbox)
        
        # 启用状态
        self.enabled_checkbox = QCheckBox("启用队列")
        self.enabled_checkbox.setChecked(self.queue_data["enabled"])
        form_layout.addRow("", self.enabled_checkbox)
        
        layout.addLayout(form_layout)
        
        # 按钮
        button_box = QDialogButtonBox(
            QDialogButtonBox.StandardButton.Save | QDialogButtonBox.StandardButton.Cancel
        )
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        layout.addWidget(button_box)
    
    def get_queue_data(self):
        """获取队列数据"""
        return {
            "name": self.name_edit.text(),
            "max_workers": self.max_workers_spinbox.value(),
            "priority": self.priority_spinbox.value(),
            "enabled": self.enabled_checkbox.isChecked()
        }


class QueuePage(QWidget):
    """队列管理页面"""
    
    def __init__(self, config, database, task_scheduler):
        super().__init__()
        self.config = config
        self.database = database
        self.task_scheduler = task_scheduler
        self.queues = []  # 队列列表
        self.queue_tasks = {}  # 队列任务映射
        self._setup_ui()
        self._load_queues()
        
        # 设置定时器更新队列状态
        self.update_timer = QTimer(self)
        self.update_timer.timeout.connect(self._update_queue_status)
        self.update_timer.start(2000)  # 2秒更新一次
        
        logging.info("队列管理页面已初始化")
    
    def _setup_ui(self):
        """设置UI"""
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(20, 20, 20, 20)
        
        # 标题
        title_label = QLabel("队列管理")
        title_label.setStyleSheet("font-size: 24px; font-weight: bold;")
        main_layout.addWidget(title_label)
        
        # 队列和任务区域
        splitter = QSplitter(Qt.Orientation.Vertical)
        
        # 队列列表区域
        queues_frame = QFrame()
        queues_frame.setFrameShape(QFrame.Shape.StyledPanel)
        queues_layout = QVBoxLayout(queues_frame)
        
        queues_header = QHBoxLayout()
        queues_header.addWidget(QLabel("队列列表"))
        
        # 新建队列按钮
        new_queue_btn = QPushButton("新建队列")
        new_queue_btn.clicked.connect(self._create_queue)
        queues_header.addWidget(new_queue_btn)
        
        # 刷新按钮
        refresh_btn = QPushButton("刷新")
        refresh_btn.clicked.connect(self._refresh_queues)
        queues_header.addWidget(refresh_btn)
        
        queues_layout.addLayout(queues_header)
        
        # 队列表格
        self.queue_table = QTableWidget()
        self.queue_table.setColumnCount(5)
        self.queue_table.setHorizontalHeaderLabels(["名称", "优先级", "并行任务数", "状态", "任务数"])
        self.queue_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.Stretch)
        self.queue_table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeMode.ResizeToContents)
        self.queue_table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeMode.ResizeToContents)
        self.queue_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeMode.ResizeToContents)
        self.queue_table.horizontalHeader().setSectionResizeMode(4, QHeaderView.ResizeMode.ResizeToContents)
        self.queue_table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        self.queue_table.setSelectionMode(QTableWidget.SelectionMode.SingleSelection)
        self.queue_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        self.queue_table.itemSelectionChanged.connect(self._queue_selected)
        self.queue_table.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self.queue_table.customContextMenuRequested.connect(self._show_queue_context_menu)
        
        queues_layout.addWidget(self.queue_table)
        
        # 队列任务区域
        tasks_frame = QFrame()
        tasks_frame.setFrameShape(QFrame.Shape.StyledPanel)
        tasks_layout = QVBoxLayout(tasks_frame)
        
        tasks_header = QHBoxLayout()
        self.queue_tasks_label = QLabel("队列任务")
        tasks_header.addWidget(self.queue_tasks_label)
        
        # 暂停队列按钮
        self.pause_queue_btn = QPushButton("暂停队列")
        self.pause_queue_btn.clicked.connect(self._pause_queue)
        tasks_header.addWidget(self.pause_queue_btn)
        
        # 恢复队列按钮
        self.resume_queue_btn = QPushButton("恢复队列")
        self.resume_queue_btn.clicked.connect(self._resume_queue)
        tasks_header.addWidget(self.resume_queue_btn)
        
        # 清空队列按钮
        self.clear_queue_btn = QPushButton("清空队列")
        self.clear_queue_btn.clicked.connect(self._clear_queue)
        tasks_header.addWidget(self.clear_queue_btn)
        
        tasks_layout.addLayout(tasks_header)
        
        # 队列任务表格
        self.tasks_table = QTableWidget()
        self.tasks_table.setColumnCount(5)
        self.tasks_table.setHorizontalHeaderLabels(["ID", "名称", "脚本", "状态", "进度"])
        self.tasks_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents)
        self.tasks_table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch)
        self.tasks_table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeMode.Stretch)
        self.tasks_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeMode.ResizeToContents)
        self.tasks_table.horizontalHeader().setSectionResizeMode(4, QHeaderView.ResizeMode.ResizeToContents)
        self.tasks_table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        self.tasks_table.setSelectionMode(QTableWidget.SelectionMode.SingleSelection)
        self.tasks_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        
        tasks_layout.addWidget(self.tasks_table)
        
        # 添加到分割器
        splitter.addWidget(queues_frame)
        splitter.addWidget(tasks_frame)
        splitter.setSizes([200, 400])
        
        main_layout.addWidget(splitter)
    
    def _load_queues(self):
        """加载队列列表"""
        # 这里应该从数据库加载队列列表
        # 目前使用模拟数据
        self.queues = [
            {
                "name": "默认队列",
                "priority": 5,
                "max_workers": 2,
                "enabled": True,
                "status": "运行中",
                "task_count": 3
            },
            {
                "name": "高优先级队列",
                "priority": 10,
                "max_workers": 4,
                "enabled": True,
                "status": "运行中",
                "task_count": 1
            },
            {
                "name": "低优先级队列",
                "priority": 1,
                "max_workers": 1,
                "enabled": False,
                "status": "暂停",
                "task_count": 5
            },
        ]
        
        # 模拟队列任务数据
        self.queue_tasks = {
            "默认队列": [
                {"id": 1, "name": "每日数据爬取", "script": "网页爬虫示例", "status": "运行中", "progress": 30},
                {"id": 2, "name": "文件处理任务", "script": "桌面自动化示例", "status": "等待中", "progress": 0},
                {"id": 3, "name": "数据分析报告", "script": "网页爬虫示例", "status": "等待中", "progress": 0},
            ],
            "高优先级队列": [
                {"id": 4, "name": "紧急数据处理", "script": "数据处理脚本", "status": "运行中", "progress": 75},
            ],
            "低优先级队列": [
                {"id": 5, "name": "系统备份", "script": "备份脚本", "status": "等待中", "progress": 0},
                {"id": 6, "name": "日志分析", "script": "日志分析脚本", "status": "等待中", "progress": 0},
                {"id": 7, "name": "数据清理", "script": "清理脚本", "status": "等待中", "progress": 0},
                {"id": 8, "name": "旧文件归档", "script": "归档脚本", "status": "等待中", "progress": 0},
                {"id": 9, "name": "报表生成", "script": "报表脚本", "status": "等待中", "progress": 0},
            ],
        }
        
        self._update_queue_table()
    
    def _update_queue_table(self):
        """更新队列表格"""
        self.queue_table.setRowCount(0)
        
        for queue in self.queues:
            row = self.queue_table.rowCount()
            self.queue_table.insertRow(row)
            
            self.queue_table.setItem(row, 0, QTableWidgetItem(queue["name"]))
            self.queue_table.setItem(row, 1, QTableWidgetItem(str(queue["priority"])))
            self.queue_table.setItem(row, 2, QTableWidgetItem(str(queue["max_workers"])))
            
            status_item = QTableWidgetItem(queue["status"])
            status_color = "#2ecc71" if queue["status"] == "运行中" else "#e74c3c"
            status_item.setForeground(QColor(status_color))
            self.queue_table.setItem(row, 3, status_item)
            
            self.queue_table.setItem(row, 4, QTableWidgetItem(str(queue["task_count"])))
    
    def _update_tasks_table(self, queue_name):
        """更新任务表格"""
        self.tasks_table.setRowCount(0)
        
        if queue_name in self.queue_tasks:
            tasks = self.queue_tasks[queue_name]
            
            for task in tasks:
                row = self.tasks_table.rowCount()
                self.tasks_table.insertRow(row)
                
                self.tasks_table.setItem(row, 0, QTableWidgetItem(str(task["id"])))
                self.tasks_table.setItem(row, 1, QTableWidgetItem(task["name"]))
                self.tasks_table.setItem(row, 2, QTableWidgetItem(task["script"]))
                
                status_item = QTableWidgetItem(task["status"])
                status_color = "#2ecc71" if task["status"] == "运行中" else "#f39c12"
                status_item.setForeground(QColor(status_color))
                self.tasks_table.setItem(row, 3, status_item)
                
                # 进度条
                progress_bar = QProgressBar()
                progress_bar.setRange(0, 100)
                progress_bar.setValue(task["progress"])
                progress_bar.setTextVisible(True)
                self.tasks_table.setCellWidget(row, 4, progress_bar)
        
        # 添加上下文菜单
        self.tasks_table.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self.tasks_table.customContextMenuRequested.connect(self._show_task_context_menu)

    def _show_task_context_menu(self, position):
        """显示任务上下文菜单"""
        current_row = self.tasks_table.currentRow()
        if current_row < 0:
            return
            
        menu = QMenu(self)
        
        # 跳转到脚本
        script_name = self.tasks_table.item(current_row, 2).text()
        goto_script_action = QAction(f"跳转到脚本: {script_name}", self)
        goto_script_action.triggered.connect(lambda: self._goto_script(script_name))
        menu.addAction(goto_script_action)
        
        menu.exec(self.tasks_table.mapToGlobal(position))

    def _goto_script(self, script_name):
        """跳转到脚本页面"""
        # 切换到脚本页面
        main_window = self.window()
        main_window.tabs.setCurrentIndex(2)  # 脚本页面的索引
        logging.info(f"跳转到脚本: {script_name}")
    
    def _queue_selected(self):
        """队列选中事件"""
        current_row = self.queue_table.currentRow()
        if current_row >= 0:
            queue_name = self.queue_table.item(current_row, 0).text()
            self.queue_tasks_label.setText(f"队列任务: {queue_name}")
            self._update_tasks_table(queue_name)
    
    def _show_queue_context_menu(self, position):
        """显示队列上下文菜单"""
        current_row = self.queue_table.currentRow()
        
        if current_row >= 0:
            menu = QMenu()
            
            # 设置队列
            settings_action = QAction("队列设置", self)
            settings_action.triggered.connect(self._edit_queue_settings)
            menu.addAction(settings_action)
            
            # 获取当前队列
            queue = self.queues[current_row]
            
            # 暂停/恢复队列
            if queue["status"] == "运行中":
                pause_action = QAction("暂停队列", self)
                pause_action.triggered.connect(lambda: self._pause_queue())
                menu.addAction(pause_action)
            else:
                resume_action = QAction("恢复队列", self)
                resume_action.triggered.connect(lambda: self._resume_queue())
                menu.addAction(resume_action)
            
            # 清空队列
            clear_action = QAction("清空队列", self)
            clear_action.triggered.connect(lambda: self._clear_queue())
            menu.addAction(clear_action)
            
            menu.exec(self.queue_table.mapToGlobal(position))
    
    def _create_queue(self):
        """创建新队列"""
        # 创建一个新的队列数据
        new_queue = {
            "name": f"新队列_{len(self.queues) + 1}",
            "priority": 5,
            "max_workers": 2,
            "enabled": True,
            "status": "运行中",
            "task_count": 0
        }
        
        # 打开设置对话框
        dialog = QueueSettingsDialog(new_queue, parent=self)
        if dialog.exec():
            queue_data = dialog.get_queue_data()
            self.queues.append(queue_data)
            self.queue_tasks[queue_data["name"]] = []
            self._update_queue_table()
            logging.info(f"已创建队列: {queue_data['name']}")
    
    def _edit_queue_settings(self):
        """编辑队列设置"""
        current_row = self.queue_table.currentRow()
        if current_row >= 0:
            queue = self.queues[current_row]
            dialog = QueueSettingsDialog(queue, parent=self)
            if dialog.exec():
                updated_data = dialog.get_queue_data()
                queue.update(updated_data)
                self._update_queue_table()
                logging.info(f"已更新队列设置: {queue['name']}")
    
    def _pause_queue(self):
        """暂停队列"""
        current_row = self.queue_table.currentRow()
        if current_row >= 0:
            queue = self.queues[current_row]
            queue["status"] = "暂停"
            self._update_queue_table()
            logging.info(f"已暂停队列: {queue['name']}")
    
    def _resume_queue(self):
        """恢复队列"""
        current_row = self.queue_table.currentRow()
        if current_row >= 0:
            queue = self.queues[current_row]
            queue["status"] = "运行中"
            self._update_queue_table()
            logging.info(f"已恢复队列: {queue['name']}")
    
    def _clear_queue(self):
        """清空队列"""
        current_row = self.queue_table.currentRow()
        if current_row >= 0:
            queue = self.queues[current_row]
            reply = QMessageBox.question(
                self, "确认清空", f"确定要清空队列 '{queue['name']}' 中的所有任务吗？",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                QMessageBox.StandardButton.No
            )
            
            if reply == QMessageBox.StandardButton.Yes:
                queue_name = queue["name"]
                self.queue_tasks[queue_name] = []
                queue["task_count"] = 0
                self._update_queue_table()
                self._update_tasks_table(queue_name)
                logging.info(f"已清空队列: {queue_name}")
    
    def _update_queue_status(self):
        """更新队列状态"""
        # 这里应该从后端获取最新的队列状态
        # 目前只是模拟进度更新
        for queue_name, tasks in self.queue_tasks.items():
            for task in tasks:
                if task["status"] == "运行中":
                    # 增加进度
                    task["progress"] += 1
                    if task["progress"] >= 100:
                        task["progress"] = 100
                        task["status"] = "已完成"
        
        # 如果当前有选中的队列，更新任务表格
        current_row = self.queue_table.currentRow()
        if current_row >= 0:
            queue_name = self.queue_table.item(current_row, 0).text()
            self._update_tasks_table(queue_name)
    
    def _refresh_queues(self):
        """刷新队列列表"""
        # 这里应该从后端获取最新的队列列表
        # 目前只是重新加载现有数据
        self._update_queue_table()
        logging.info("已刷新队列列表")